<template>
	<div>
		<main-content
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					label-width="auto"
					class="flex-warp-container"
				>
					<el-form-item
						label="所属商户:"
						class="flex-row-container"
						label-width="77px"
					>
						<merchant-select
							v-model="queryData.merchantId"
							placeholder="默认选择全部"
						></merchant-select>
					</el-form-item>
					<el-form-item
						:label="`代理账号:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.proxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>

					<el-form-item
						:label="`${$t(
							'funds.fund_audit.parent_proxy_account'
						)}:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.parentProxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`${$t(
							'funds.fund_audit.belong_general_agent'
						)}:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.topProxyName"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						label-width="100px"
						:label="$t('common.business_model') + ':'"
						prop="businessModel"
					>
						<el-select
							v-model="queryData.businessModel"
							placeholder="默认选择全部"
							clearable
						>
							<el-option
								v-for="(item, index) in businessModelList"
								:key="index"
								:label="item.label"
								:value="item.value"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							icon="el-icon-plus"
							v-if="hasPermission('90810091')"
							type="warning"
							size="medium"
							@click="addFn"
						>
							新增
						</el-button>
						<el-button
							size="medium"
							v-if="hasPermission('90810094')"
							type="warning"
							@click="allocationFn('credit')"
						>
							信用线默认配置
						</el-button>
						<el-button
							size="medium"
							v-if="hasPermission('90810095')"
							type="warning"
							@click="allocationFn('cash')"
						>
							现金线默认配置
						</el-button>
					</el-form-item>
				</el-form>
			</template>
			<template slot="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="dataList"
					:max-height="tableHeight"
					highlight-current-row
					style="width: 100%"
					:header-cell-style="getRowClass"
				>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`代理账号`"
					>
						<template slot-scope="scope">
							{{ scope.row.proxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`直属上级`"
					>
						<template slot-scope="scope">
							{{ scope.row.parentProxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`所属总代`"
					>
						<template slot-scope="scope">
							{{ scope.row.topProxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`所属商户`"
					>
						<template slot-scope="scope">
							{{ scope.row.merchantName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						width="200px"
						prop="sort"
						align="center"
						:label="`业务模式`"
					>
						<template slot-scope="scope">
							{{
								businessModelMap[scope.row.businessModel] || '-'
							}}
						</template>
					</el-table-column>

					<el-table-column
						prop="memberCustomerConfig"
						width="200px"
						align="center"
						:label="'会员客服入口开关'"
					>
						<template slot-scope="scope">
							<el-switch
								:value="scope.row.memberCustomerConfig"
								:active-value="1"
								:disabled="!hasPermission('90810096')"
								:inactive-value="0"
								@change="
									updatedStatus(
										scope.row,
										'memberCustomerConfig'
									)
								"
							/>
						</template>
					</el-table-column>
					<el-table-column
						prop="proxyCustomerConfig"
						align="center"
						width="200px"
						:label="'代理客服入口开关'"
					>
						<template slot-scope="scope">
							<el-switch
								:value="scope.row.proxyCustomerConfig"
								:active-value="1"
								:inactive-value="0"
								:disabled="!hasPermission('90810096')"
								@change="
									updatedStatus(
										scope.row,
										'proxyCustomerConfig'
									)
								"
							/>
						</template>
					</el-table-column>
					<el-table-column
						prop="createdBy"
						align="center"
						width="200px"
						:label="'创建人'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.createdBy || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						width="200px"
						:label="'创建时间'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.createdAt || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedBy"
						align="center"
						width="200px"
						:label="'最后操作人'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.updatedBy || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedAt"
						width="200px"
						align="center"
						:label="'最后操作时间'"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.updatedAt || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="auditStep"
						width="200px"
						align="center"
						:label="$t('common.actions')"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="hasPermission('90810092')"
								type="primary"
								size="medium"
								@click="openEditDialog(scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="hasPermission('90810093')"
								type="primary"
								class="action-button"
								@click="handleDelete(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="queryData.pageSize"
					:page-sizes="pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
			<el-dialog
				:visible.sync="visibleDialog"
				:title="ruleFormType === 'edit' ? '编辑' : `新增`"
				:width="getWidth('500px')"
			>
				<el-form
					ref="dialogFormRef"
					:model="formData"
					:rules="editFormRules"
					:close-on-click-modal="false"
				>
					<el-form-item
						label-width="100px"
						:label="`所属商户:`"
						prop="merchantId"
					>
						<merchant-select
							v-if="ruleFormType === 'add'"
							style="width: 280px"
							v-model="formData.merchantId"
							:placeholder="$t('common.please_choose')"
						></merchant-select>
						<span v-else>{{ formData.merchantName }}</span>
					</el-form-item>
					<el-form-item
						label-width="100px"
						:label="`代理账号:`"
						prop="proxyName"
					>
						<el-input
							v-if="ruleFormType === 'add'"
							v-model.trim="formData.proxyName"
							style="width: 280px"
							:placeholder="'请输入'"
							v-input="{ name: 'num_alp' }"
							@blur="getAgentInfo"
						></el-input>
						<span v-else>{{ formData.proxyName }}</span>
					</el-form-item>
					<el-form-item
						label-width="100px"
						:label="$t('common.business_model') + ':'"
						prop="businessModel"
					>
						<el-select
							style="width: 280px"
							disabled
							v-model="formData.businessModel"
							:placeholder="$t('common.please_choose')"
						>
							<el-option
								v-for="(item, index) in businessModelList"
								:key="index"
								:label="item.label"
								:value="item.value"
							></el-option>
						</el-select>
						<!-- <span>
							{{
								businessModelMap[formData.businessModel] || '-'
							}}
						</span> -->
					</el-form-item>

					<div class="flex" style="justify-content: space-around">
						<el-form-item
							label-width="140px"
							:label="`会员客服入口开关:`"
							prop="memberCustomerConfig"
						>
							<el-switch
								v-model="formData.memberCustomerConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
						<el-form-item
							label-width="140px"
							:label="`代理客服入口开关:`"
							prop="proxyCustomerConfig"
						>
							<el-switch
								v-model="formData.proxyCustomerConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
					</div>
				</el-form>
				<template #footer>
					<span>
						<el-button @click="visibleDialog = false">
							{{ $t('common.cancel') }}
						</el-button>
						<el-button type="primary" @click="handleSubmit">
							{{ $t('common.confirm') }}
						</el-button>
					</span>
				</template>
			</el-dialog>
			<el-dialog
				:visible.sync="allocationDialog"
				:title="type == 'credit' ? '信用线默认配置' : '现金线默认配置'"
				:width="getWidth('500px')"
			>
				<el-form
					ref="allocationFormRef"
					:model="formData"
					:rules="editFormRules"
					label-width="auto"
					:close-on-click-modal="false"
				>
					<div class="flex" style="justify-content: space-around">
						<el-form-item
							:label="`会员客服入口开关:`"
							prop="memberCustomerConfig"
						>
							<el-switch
								v-model="formData.memberCustomerConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
						<el-form-item
							:label="`代理客服入口开关:`"
							prop="proxyCustomerConfig"
						>
							<el-switch
								v-model="formData.proxyCustomerConfig"
								inline-prompt
								size="large"
								:active-value="1"
								:inactive-value="0"
							/>
						</el-form-item>
					</div>
				</el-form>
				<template #footer>
					<span>
						<el-button @click="allocationDialog = false">
							{{ $t('common.cancel') }}
						</el-button>
						<el-button type="primary" @click="allocationSubmit">
							{{ $t('common.confirm') }}
						</el-button>
					</span>
				</template>
			</el-dialog>
		</main-content>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'

export default {
  name: routerNames.customerConfig,
  components: {
    MainContent,
    GoogleKeyInput: () => import('@/components/GoogleKeyInput')
  },
  mixins: [list],
  data() {
    this.loadData = this.throttle(this.loadData, 1000)
    return {
      type: '',
      isShowdialog: false,
      ruleFormType: '',
      ruleFormValue: '',
      rowId: '',
      tableHeight: 480,
      otherDependenComponents: [],
      queryData: {
        pageNum: 1,
        pageSize: 100,
        merchantId: '',
        businessModel: '',
        parentProxyName: '',
        proxyName: '',
        topProxyName: ''
      },
      formData: {
        proxyName: '',
        merchantId: '',
        businessModel: '',
        memberCustomerConfig: '',
        proxyCustomerConfig: ''
      },
      dataList: [],
      visibleDialog: false,
      allocationDialog: false,
      editFormRules: {
        proxyName: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        merchantId: [
          {
            required: true,
            message: '请选择',
            trigger: ['change']
          }
        ],
        memberCustomerConfig: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
        proxyCustomerConfig: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
        businessModel: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ]
      },
      businessModelList: [
        {
          label: '信用模式',
          value: 2
        },
        {
          label: '现金模式',
          value: 1
        }
      ],
      businessModelMap: {
        0: '信用模式',
        1: '现金模式',
        2: '信用模式'
      }
    }
  },
  methods: {
    getAgentInfo() {
      if (!this.formData.proxyName) return
      const params = {
        merchantId: this.formData.merchantId,
        proxyName: this.formData.proxyName
      }
      this.$api
        .customerConfigProxyVerify(params)
        .then(async (res) => {
          if (res.data) {
            this.formData.businessModel = res.data.businessModel
            this.$api
              .customerConfigDefaultConfig({
                businessModel: this.formData.businessModel
              })
              .then((res) => {
                if (res.code === 200) {
                  this.formData.memberCustomerConfig = res.data.memberCustomerConfig || 0
                  this.formData.proxyCustomerConfig = res.data.proxyCustomerConfig || 0
                }
              })
          } else {
            this.$message.error(this.$t('agent.rule_agent_tip'))
          }
        })
        .catch(() => {
          this.formData.businessModel = ''
          this.formData.memberCustomerConfig = 0
          this.formData.proxyCustomerConfig = 0
        })
    },
    getGoogleKey(data) {
      this.isShowdialog = false
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      if (this.ruleFormType === 'add' || this.ruleFormType === 'edit') {
        const params = {
          businessModel: this.type == 'cash' ? 1 : 2,
          merchantId: this.formData.merchantId,
          proxyName: this.formData.proxyName,
          memberCustomerConfig: this.formData.memberCustomerConfig,
          proxyCustomerConfig: this.formData.proxyCustomerConfig,
          haiyueAuthCode: data
        }
        if (this.ruleFormType === 'edit') {
          params.id = this.rowId
        }
        const apiName = this.ruleFormType === 'edit'
          ? 'customerConfigUpdate'
          : 'customerConfigAdd'
        this.$api[apiName](params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(
                this.$t('common.action_success')
              )
              this.loadData()
              this.visibleDialog = false
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      } else if (this.ruleFormType === 'del') {
        this.$api.customerConfigDelete({ id: this.rowId, haiyueAuthCode: data }).then(() => {
          this.loadData()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          loading.close()
        }).catch(() => {
          loading.close()
        })
      } else if (this.ruleFormType === 'allocation') {
        const params = {
          businessModel: this.type == 'cash' ? 1 : 2,
          memberCustomerConfig: this.formData.memberCustomerConfig,
          proxyCustomerConfig: this.formData.proxyCustomerConfig,
          haiyueAuthCode: data
        }
        this.$api
          .customerConfigUpdateDefaultConfig(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(
                this.$t('common.modify_success')
              )
              this.loadData()
              this.allocationDialog = false
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      } else if (this.ruleFormType === 'memberCustomerConfig' || this.ruleFormType === 'proxyCustomerConfig') {
        this.$api.customerConfigUpdate({
          id: this.rowId,
          [this.ruleFormType]: this.ruleFormValue,
          haiyueAuthCode: data
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success(this.$t('common.modify_success'))
            this.loadData()
          }
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    },
    backPrevStep() {
      this.isShowdialog = false
    },
    cleanBlankSpace(key, key1) {
      if (this[key][key1]) {
        this[key][key1] = (this[key][key1] + '').replace(/\s+/g, '')
      }
    },
    search() {
      this.pageNum = 1
      this.queryData.pageNum = 1
      this.loadData()
    },
    loadData() {
      this.loading = true
      const params = this.getParams({
        ...this.queryData,
        ...params
      })
      this.$api
        .customerConfigList(params)
        .then((res) => {
          this.loading = false
          const {
            code,
            data: { record, totalRecord },
            msg
          } = res
          if (code === 200) {
            this.dataList = record || [{}, {}]
            this.total = totalRecord || 0
          } else {
            this.loading = false
            this.$message({
              message: msg,
              type: 'error'
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    reset() {
      this.queryData = {
        pageNum: 1,
        pageSize: 100,
        merchantId: '',
        businessModel: '',
        parentProxyName: '',
        proxyName: '',
        topProxyName: ''
      }
      this.pageNum = 1
      this.type = ''
      this.isShowdialog = false
      this.ruleFormType = ''
      this.ruleFormValue = ''
      this.rowId = ''
      this.loadData()
    },
    updatedStatus(row, name) {
      this.rowId = row.id
      this.ruleFormType = name
      this.ruleFormValue = row[name] == 0 ? 1 : 0
      if (this.ruleFormType === 'memberCustomerConfig' || this.ruleFormType === 'proxyCustomerConfig') {
        this.isShowdialog = true
      } else {
        const params = {
          id: row.id
        }
        params[name] = row[name] == 0 ? 1 : 0
        this.$api.updateCreditLineConfigUpdate(params).then((res) => {
          if (res.code === 200) {
            this.$message.success(this.$t('common.modify_success'))
            this.loadData()
          }
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        `<strong>是否删除该条配置?</strong></br><span style='font-size:12px;color:#c1c1c1'>请谨慎操作</span>`,
        '确认提示',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.rowId = row.id
        this.ruleFormType = 'del'
        this.isShowdialog = true
      })
    },
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value
      this.loadData()
    },
    handleCurrentChange(value) {
      this.pageNum = value
      this.loadData()
    },
    openEditDialog(row) {
      this.$refs.dialogFormRef && this.$refs.dialogFormRef.resetFields()
      this.ruleFormType = 'edit'
      this.rowId = row.id
      this.formData = {
        ...row
      }
      this.visibleDialog = true
    },
    addFn() {
      this.formData = {
        proxyName: '',
        merchantId: '',
        businessModel: '',
        memberCustomerConfig: '',
        proxyCustomerConfig: ''
      }
      this.$refs.dialogFormRef && this.$refs.dialogFormRef.resetFields()
      this.ruleFormType = 'add'
      this.visibleDialog = true
    },
    allocationFn(val) {
      this.type = val
      this.$refs.allocationFormRef &&
        this.$refs.allocationFormRef.resetFields()
      this.allocationDialog = true
      this.ruleFormType = 'allocation'
      this.$api
        .customerConfigDefaultConfig({
          businessModel: this.type == 'cash' ? 1 : 2
        })
        .then((res) => {
          if (res.code === 200) {
            this.formData = res.data
          }
        })
    },
    handleSubmit() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {
          this.isShowdialog = true
        }
      })
    },
    allocationSubmit() {
      this.$refs.allocationFormRef.validate((valid) => {
        if (valid) {
          this.isShowdialog = true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .caret-wrapper {
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}
.data-refresh {
	margin-top: 0;
	padding-bottom: 20px;
}
.look {
	//background-color: #00BFBF;
	//border-color: #00BFBF;
	color: #00bfbf;
}
</style>
